/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package applety;

import data.Data;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author Riso-Desktop
 */
public class hra4 extends javax.swing.JApplet implements Runnable {

    Thread vlakno;
    boolean ide = true;
    boolean nacitane = false;
    int body = 0;
    boolean skontrolovane = false;
    String id;
    /**
     * Initializes the applet hra4
     */
    int a = -1;
    int b = -1;
    int co = -1;
    int nazovcoho = -1;
    int kto = -1;
    int pocetPrikladov = 1;
    String[] mena = {
        "Bart",
        "Homer",
        "Milhaus",
        "Ralf",
        "Krasty"
    };
    String[] spravili = {
        "ti kúpil",
        "ti daroval",
        "ti zobral",
        "ti ukradol",
        "ti vzal"
    };
    String[] coho = {
        "cukríkov",
        "lízatiek",
        "jabĺčok",
        "orechov",
        "perníkov"
    };
    String[] coho2 = {
        "cukríky",
        "lízatká",
        "jabĺčka",
        "orechy",
        "perníky"
    };
    String[] coho1 = {
        "cukrík",
        "lízatko",
        "jabĺčko",
        "orech",
        "perník"
    };

    private void nacitajData(Data data) {

        data.string1 = co + ";" + nazovcoho + ";" + kto + ";" + a + ";" + b + ";" + body + ";" + pocetPrikladov;
        data.string1 = data.typ + ";" + data.string1 + ";";


    }

    public void vymysliUlohu() {
        if (pocetPrikladov == 6) {
            pocetPrikladov = 1;
        }
        jLabel3.setText("Príklad: " + pocetPrikladov + "/5");
        jLabel2.setText("");
        jTextArea1.setText("");
        jTextField1.setText("");
        int cislo = (int) (11 * Math.random()) + 10;
        if (nazovcoho < 0) {
            nazovcoho = (int) (5 * Math.random()) + 0;
        }
        int n = (int) (5 * Math.random()) + 0;
        if (a < 0) {
            a = cislo;
        }
        if (a < 5) {
            jTextArea1.append("Máš " + a + " " + coho2[nazovcoho] + ".\n");
        } else {
            jTextArea1.append("Máš " + a + " " + coho[nazovcoho] + ".\n");
        }
        cislo = (int) (11 * Math.random()) + 1;
        if (kto < 0) {
            kto = (int) (5 * Math.random()) + 0;
        }
        jTextArea1.append(mena[kto] + " ");
        n = (int) (5 * Math.random()) + 0;
        if (co < 0) {
            co = n;
        }
        if (b < 0) {
            b = cislo;
        }
        jTextArea1.append(spravili[co] + " " + b);
        if (b < 5 && b != 1) {
            jTextArea1.append(" " + coho2[nazovcoho]);
        } else if (b == 1) {
            jTextArea1.append(" " + coho1[nazovcoho]);
        } else {
            jTextArea1.append(" " + coho[nazovcoho]);
        }
        jTextArea1.append(".\n");
        jTextArea1.append("Koľko " + coho[nazovcoho] + " máš teraz?");

    }

    @Override
    public void init() {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(hra4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(hra4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(hra4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(hra4.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        vlakno = new Thread(this);
        this.setSize(450, 200);
        initComponents();
        vymysliUlohu();
        vlakno.start();
    }

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jTextField1 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        jTextArea1.setColumns(20);
        jTextArea1.setEditable(false);
        jTextArea1.setRows(5);
        jTextArea1.setAutoscrolls(false);
        jTextArea1.setBorder(null);
        jTextArea1.setFocusable(false);
        jTextArea1.setRequestFocusEnabled(false);
        jTextArea1.setVerifyInputWhenFocusTarget(false);
        jScrollPane1.setViewportView(jTextArea1);

        jLabel1.setText("Odpoveď:");

        jButton1.setText("Skontroluj");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Nová úloha");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel3.setText("Príklad: 1/5");

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/animated-gifs-simpsons-036.gif"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jButton2)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(34, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        a = -1;
        b = -1;
        co = -1;
        nazovcoho = -1;
        kto = -1;
        pocetPrikladov++;
        vymysliUlohu();
        skontrolovane = false;

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if (skontrolovane == true) {
            JOptionPane.showMessageDialog(rootPane, "Tento pokus je už skontrolovaný. Klikni na 'Nová Úloha'");
            return;
        }
        try {

            if (co < 2) {
                if (a + b == Integer.parseInt(jTextField1.getText())) {
                    jLabel2.setText("Správne");
                    body++;
                } else {
                    jLabel2.setText("Nesprávne");
                }
            } else {
                if (a - b == Integer.parseInt(jTextField1.getText())) {
                    jLabel2.setText("Správne");
                    body++;
                } else {
                    jLabel2.setText("Nesprávne");
                }
            }

            skontrolovane = true;
            if (pocetPrikladov == 5) {
                zapisBody();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Odpoveď môže obsahovať len čísla.");
        }
    }//GEN-LAST:event_jButton1ActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables

    private void zapisData(String data) {
        String d = data;
        if (d.length() != 1 && d.substring(0, 2).equals("4;")) {
            d = d.substring(2);
            co = Integer.parseInt(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";") + 1);
            nazovcoho = Integer.parseInt(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";") + 1);
            kto = Integer.parseInt(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";") + 1);
            a = Integer.parseInt(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";") + 1);
            b = Integer.parseInt(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";") + 1);
            body = Integer.parseInt(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";") + 1);
            pocetPrikladov = Integer.parseInt(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";") + 1);
            System.out.println(co + ";" + nazovcoho + ";" + kto + ";" + a + ";" + b + ";" + body + ";" + pocetPrikladov);
            vymysliUlohu();
        }
    }

    private synchronized void zapisBody() {
        try {

            URL servlet = new URL("http://localhost:8080/Portalpredeti/zapisBody");
            URLConnection con = servlet.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-java-serialized-object");

            OutputStream outstream = con.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outstream);
            oos.writeObject("4"); //cislo ulohy
            oos.writeObject(id);
            oos.writeObject(body + "/" + "5");
            body = 0;
            oos.flush();
            oos.close();

            InputStream instr = con.getInputStream();
            ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
            String s = (String) inputFromServlet.readObject();
            inputFromServlet.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (ide) {
                Data d = new Data(4);
                if (!skontrolovane) {
                    nacitajData(d);
                }
                URL servlet = new URL("http://localhost:8080/Portalpredeti/zapisDoDB");
                URLConnection con = servlet.openConnection();
                con.setDoOutput(true);
                con.setDoInput(true);
                con.setUseCaches(false);
                con.setRequestProperty("Content-Type", "application/x-java-serialized-object");
                id = getParameter("ID");
                // TODO: toto ID na konci zmazať
                //id = "1";
                if (!nacitane) {
                    OutputStream outstream = con.getOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(outstream);
                    oos.writeObject("nacitat");

                    oos.writeObject(id);
                    oos.writeObject(d);
                    oos.flush();
                    oos.close();

                    InputStream instr = con.getInputStream();
                    ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
                    String s = (String) inputFromServlet.readObject();
                    if (s != null) {
                        zapisData(s);
                    }
                    inputFromServlet.close();
                    repaint();
                    nacitane = true;
                } else if (!skontrolovane) {
                    OutputStream outstream = con.getOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(outstream);
                    oos.writeObject("zapis");

                    oos.writeObject(id);
                    oos.writeObject(d);
                    oos.flush();
                    oos.close();
                    InputStream instr = con.getInputStream();
                    ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
                    String c = (String) inputFromServlet.readObject();
                    System.out.println(c);
                    inputFromServlet.close();

                }
                vlakno.sleep(10000);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
